'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('=== cleanDuplicateMessages 开始 ===');
  
  try {
    // 查询所有互动消息
    const allMessagesRes = await db.collection('interaction-messages')
      .orderBy('create_time', 'desc')
      .get();
    
    console.log('总消息数:', allMessagesRes.data.length);
    
    // 按 receiver_id, sender_id, post_id, type 分组
    const messageGroups = {};
    const duplicates = [];
    
    allMessagesRes.data.forEach(message => {
      const key = `${message.receiver_id}_${message.sender_id}_${message.post_id}_${message.type}`;
      
      if (!messageGroups[key]) {
        messageGroups[key] = [];
      }
      messageGroups[key].push(message);
    });
    
    // 找出重复的消息组
    Object.keys(messageGroups).forEach(key => {
      const group = messageGroups[key];
      if (group.length > 1) {
        // 保留最新的消息，删除其他的
        group.sort((a, b) => b.create_time - a.create_time);
        const keepMessage = group[0];
        const deleteMessages = group.slice(1);
        
        duplicates.push({
          key: key,
          keep: keepMessage,
          delete: deleteMessages
        });
      }
    });
    
    console.log('发现重复消息组:', duplicates.length);
    
    // 删除重复消息
    let deletedCount = 0;
    for (const duplicate of duplicates) {
      for (const deleteMsg of duplicate.delete) {
        await db.collection('interaction-messages').doc(deleteMsg._id).remove();
        deletedCount++;
        console.log('删除重复消息:', deleteMsg._id);
      }
    }
    
    return {
      code: 200,
      msg: '清理完成',
      data: {
        totalMessages: allMessagesRes.data.length,
        duplicateGroups: duplicates.length,
        deletedCount: deletedCount
      }
    };
    
  } catch (e) {
    console.error('清理重复消息失败:', e);
    return {
      code: 500,
      msg: '清理失败: ' + e.message
    };
  }
}; 